<template>
  <el-dialog
    v-model="dialogVisible"
    @close="resetCaptcha"
    title=""
    :append-to-body="true"
    width="380"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <div class="text-2xl font-semibold text-center mb-[25px]">账号登录</div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="账号登录" name="first">
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="loginRules"
          class="register-form"
          v-if="activeName === 'first'"
        >
          <el-form-item class="flex items-center mt-[10px]" prop="userName">
            <el-input
              v-model="userForm.userName"
              class="w-[280px!important] m-auto"
              type="text"
              :prefix-icon="UserFilled"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item class="flex items-center mt-[10px]" prop="password">
            <el-input
              v-model="userForm.password"
              class="w-[280px!important] m-auto mt-[15px]"
              type="password"
              :prefix-icon="Lock"
              placeholder="请输入密码"
            />
          </el-form-item>
          <el-form-item class="ml-[36px] mt-[10px] h-[30px] flex items-center">
            <el-checkbox v-model="userForm.InternalUsers" size="small"
              >内部用户
            </el-checkbox>
            <el-checkbox v-model="userForm.RememberPassword" size="small"
              >记住密码</el-checkbox
            >
            <span
              v-show="!userForm.InternalUsers"
              class="cursor-pointer text-[#f07700] ml-[60px]"
              @click="retrievePssword"
              >忘记密码</span
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="手机登录" name="second">
        <el-form
          ref="phoneFormRef"
          :model="phoneForm"
          :rules="loginRules"
          class="register-form"
          v-if="activeName === 'second'"
        >
          <el-select
            v-model="userType"
            placeholder="请选择用户类型"
            class="w-[280px!important] ml-[10%] borderless"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-form-item class="flex items-center mt-[25px]" prop="mobilePhone">
            <el-input
              v-model="phoneForm.mobilePhone"
              class="w-[280px!important] m-auto"
              type="text"
              :prefix-icon="Iphone"
              placeholder="请输入手机号码"
            />
          </el-form-item>
          <el-form-item class="flex items-center mt-[10px]" prop="code">
            <el-input
              v-model="phoneForm.code"
              class="w-[145px!important] m-auto mt-[10px]"
              type="text"
              :prefix-icon="ChatDotRound"
              placeholder="请输入验证码"
            />
            <el-button
              type="primary"
              :disabled="countdown > 0"
              @click="getCaptcha"
              class="mt-[10px] mr-[35px]"
              >{{
                countdown > 0 ? `${countdown}秒后重试` : "获取验证码"
              }}</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="m-auto text-center">
      <el-button
        type="primary"
        @click="Login(activeName == 'first' ? userFormRef : phoneFormRef)"
        class="w-[280px] mt-[30px]"
        >登录</el-button
      >
      <div
        class="w-[300px] text-xs ml-[12px] mt-[10px] text-right cursor-pointer"
        @click="toggleRegister"
      >
        没有账号,<span style="color: #f07700">去注册 </span
        ><img
          class="inline-flex"
          style="margin-top: -3px"
          src="@renderer/assets/images/qu_jian_tou.png"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, defineEmits, reactive, onMounted } from "vue";
import { useUserStore } from "@renderer/store/modules/user";
import {
  loginCache,
  getSMSCode,
  loginByPwd,
  sendCode,
  loginByPhone,
} from "@renderer/api/login";
import {
  encryptExternalUsers,
  encryptTransmit,
} from "@renderer/utils/jsencrypt";
import {
  UserFilled,
  Lock,
  Iphone,
  ChatDotRound,
} from "@element-plus/icons-vue";
import type { TabsPaneContext, FormInstance, FormRules } from "element-plus";
const activeName = ref("first");
const countdown = ref(0);
const { ipcRenderer } = window;
const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event);
};

const userStore = useUserStore();
const hanldRegister = ref(false);
const reset = ref(false);
const props = defineProps({
  showLogin: {
    type: Boolean,
    default: false,
  },
  hasLogin: {
    type: Boolean,
    default: false,
  },
});

const userType = ref();
const options = [
  {
    value: "1",
    label: "内部用户",
  },
  {
    value: "2",
    label: "外部用户",
  },
];
const userFormRef = ref<FormInstance>();
interface RuleForm {
  userName: string;
  password: string;
  confirmPassword: string;
  mobilePhone: string;
  code: string;
  InternalUsers: string;
  RememberPassword: string;
}
// 初始化
const userForm = reactive<RuleForm>({
  userName: "",
  password: "",
  InternalUsers: "",
  confirmPassword: "",
  mobilePhone: "",
  code: "",
  RememberPassword: "",
});
onMounted(() => {
  let user = ipcRenderer.sendSync("getStore", "user");
  // console.log("user", user);
  if (user) {
    userForm.userName = JSON.parse(user).userName;
    userForm.password = JSON.parse(user).password;
    userForm.RememberPassword = JSON.parse(user).RememberPassword;
  }
});
const phoneFormRef = ref<FormInstance>();
// 初始化
const phoneForm = reactive<RuleForm>({
  confirmPassword: "",
  mobilePhone: "",
  code: "",
  InternalUsers: "",
  userName: "",
  password: "",
  RememberPassword: "",
});
// 表单校验
const loginRules = reactive<FormRules<RuleForm>>({
  userName: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
  mobilePhone: [
    { required: true, trigger: "blur", message: "请输入手机号" },
    {
      pattern: /^1[3|4|5|7|8|9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
});
const emit = defineEmits([
  "update:showLogin",
  "event",
  "goRegister",
  "goRewrite",
]);
const toggleRegister = () => {
  emit("goRegister", true);
  hanldRegister.value = true;
};

let dialogVisible = computed({
  get() {
    return props.showLogin;
  },
  set(value: boolean) {
    emit("update:showLogin", value);
  },
});
const getCaptcha = async () => {
  if (userType.value == 1) {
    // 调用获取验证码的API或逻辑
    if (phoneForm.mobilePhone) {
      getCountdown();
      //调取验证码接口
      getSMSCode(phoneForm.mobilePhone)
        .then((res) => {})
        .catch((e) => {
          clearInterval(countdown.value);
        });
    } else {
      ElMessage.error("请先输入手机号码");
    }
  } else if (userType.value == 2) {
    if (phoneForm.mobilePhone) {
      getCountdown();
      //调取验证码接口
      sendCode(phoneForm.mobilePhone)
        .then((res) => {})
        .catch((e) => {
          clearInterval(countdown.value);
        });
    } else {
      ElMessage.error("请先输入手机号码");
    }
  } else {
    ElMessage.error("请先选择用户类型");
  }
};
// 短信倒計時
const getCountdown = () => {
  countdown.value = 60; // 假设倒计时60秒
  const intervalId = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(intervalId);
    }
  }, 1000);
};
const retrievePssword = () => {
  reset.value = true;
  emit("goRewrite");
};

// 登录按钮
const Login = async (formEl: FormInstance | undefined) => {
  console.log(formEl);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(activeName.value);
      //用户名密码登录
      if (activeName.value == "first") {
        if (userForm.InternalUsers) {
          const username = userForm.userName;
          const password = encryptTransmit(userForm.password);
          // 基础平台登录
          loginCache(username, password, null, null).then(
            async (response: any) => {
              if (response.code === 200) {
                ElMessage.success("登录成功");
                setToken(response.data.token);
                userStore.setLoginStatus(true);
                userStore.toggleShowLogin(false);
                await userStore.getUserInfo();
                remPassword(userForm.RememberPassword);
                dialogVisible.value = false;
              } else {
                ElMessage.error(response.msg);
              }
            }
          );
        } else {
          const username = userForm.userName;
          const password = encryptExternalUsers(userForm.password);
          // 外部登录
          loginByPwd(username, password).then(async (response: any) => {
            if (response.code === 200) {
              ElMessage.success("登录成功");
              setToken(response.data.token);
              userStore.setLoginStatus(true);
              userStore.toggleShowLogin(false);
              await userStore.getUserInfo();
              remPassword(userForm.RememberPassword);
              dialogVisible.value = false;
            } else {
              ElMessage.error(response.msg);
            }
          });
        }
      } else {
        if (userType.value == 1) {
          // 基础平台登录
          loginCache(null, null, phoneForm.mobilePhone, phoneForm.code).then(
            async (response: any) => {
              if (response.code === 200) {
                ElMessage.success("登录成功");
                setToken(response.data.token);

                userStore.setLoginStatus(true);
                userStore.toggleShowLogin(false);
                await userStore.getUserInfo();

                dialogVisible.value = false;
              } else {
                ElMessage.error(response.msg);
              }
            }
          );
        } else {
          // 外部登录
          loginByPhone(phoneForm.mobilePhone, phoneForm.code).then(
            async (response: any) => {
              if (response.code === 200) {
                ElMessage.success("登录成功");
                setToken(response.data.token);

                userStore.setLoginStatus(true);
                userStore.toggleShowLogin(false);
                await userStore.getUserInfo();

                dialogVisible.value = false;
              } else {
                ElMessage.error(response.msg);
              }
            }
          );
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const setToken = (token: string) => {
  localStorage.setItem("token", token);
  localStorage.setItem("user", JSON.stringify(userForm));
  ipcRenderer.sendSync("setStore", {
    key: "token",
    value: token,
  });
};
//记住密码
function remPassword(RememberPassword) {
  if (RememberPassword) {
    localStorage.setItem("user", JSON.stringify(userForm));
    let flag = ipcRenderer.sendSync("setStore", {
      key: "user",
      value: JSON.stringify(userForm),
    });
    if (!flag) ElMessage.warning("账号密码保存失败");
    console.log(ipcRenderer.sendSync("getStore", "user"));
  } else {
    localStorage.removeItem("user");
    ipcRenderer.sendSync("deleteStore", "user");
  }
}
// 弹窗关闭
const resetCaptcha = (formEl: FormInstance | undefined) => {
  userStore.toggleShowLogin(false);
  if (!formEl) return;
  formEl.resetFields();
  countdown.value = 0;
  activeName.value = "first";
};
</script>

<style scoped lang="scss">
:deep(.el-input__wrapper) {
  background: #373333 !important;
  box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color))
    inset;
}

.el-checkbox:last-of-type {
  margin-right: 12px;
}

.el-checkbox {
  margin-right: 10px;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

:deep(.el-tabs__nav-wrap:after) {
  background: none;
}

:deep(.el-tabs__nav) {
  margin-left: 20px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 700;
  padding: 0 10px;
}
//获取验证码颜色修改
.el-button.is-disabled,
.el-button.is-disabled:hover {
  background-color: #589bdf;
  background-image: none;
  border-color: #4f9ae7;
  color: var(--el-button-disabled-text-color);
  cursor: not-allowed;
}

/*去掉tabs底部的下划线*/
:deep(.el-tabs__nav-wrap::after) {
  position: static !important;
}

:deep(.el-form-item__error) {
  left: 36px;
  padding-top: 5px;
}

:deep(.el-select__wrapper) {
  background-color: #373333;
  border: none !important;
  box-shadow: none !important;
}
:deep(.el-select-dropdown .el-select-dropdown__wrap) {
  background-color: #373333;
  border: none !important;
  box-shadow: none !important;
}
</style>
